// Description: Generates embed/integrated-index.html from embed/integrated-template.html
// NPM Usage: npm run build:integrated -- --siteId <siteId> [--pageId <pageId>] [--baseUrl <baseUrl>]
// Run npm run build:integrated -- --help for more information.
// This is used by Cypress to generate ad-hoc embed/integrated-index.html for testing.

const fs = require('fs')
const inputFile = './embed/integrated-template.html'
const outputFile = './embed/integrated-index.html'

const argv = require('yargs/yargs')(process.argv.slice(2))
  .usage('Usage: $0 --siteId <siteId> [--pageId <pageId>] [--baseUrl <baseUrl>]')
  .option('siteId', {
    describe: 'The site ID, generated by the server',
    type: 'string',
    demandOption: true,
  })
  .option('pageId', {
    describe: 'The page ID, generated by the user',
    type: 'string',
    default: 'PAGE_ID',
  })
  .option('baseUrl', {
    alias: 'url',
    describe: 'The base URL',
    type: 'string',
    default: process.env.BASE_URL || process.env.CYPRESS_BASE_URL || 'http://localhost',
  }).argv

fs.readFile(inputFile, 'utf8', (err, data) => {
  if (err) throw err

  const replacedData = data
    .replace(/<%= site_id %>/g, argv.siteId)
    .replace(/<%= page_id %>/g, argv.pageId)
    .replace(/<%= base_url %>/g, argv.baseUrl)

  fs.writeFile(outputFile, replacedData, 'utf8', (err) => {
    if (err) throw err
    console.log(`Generated ${outputFile} with Site ID ${argv.siteId}`)
  })
})
